package com.wind.cqboot.plugin;

import java.util.Date;
import java.util.Map;
import java.util.Random;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wind.cqboot.consts.AlApiConst;
import com.wind.cqboot.domain.Hothub;
import com.wind.cqboot.utils.HttpUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import net.lz1998.pbbot.bot.Bot;
import net.lz1998.pbbot.bot.BotPlugin;
import onebot.OnebotEvent;

/**
 * <p>File：TophubPlugin.java</p>
 * <p>Title: 今日热搜</p>
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2020 2020-8-7 14:43:27</p>
 * <p>Company: zmrit.com </p>
 * @author zmr
 * @version 1.0
 */
@Component
public class TophubPlugin extends BotPlugin
{
    private static Map<String, Hothub> hotMap = Maps.newHashMap();

    @Value("${alapi.token}")
    private String                     ALAPI_TOKEN;

    @Override
    public int onGroupMessage(@NotNull Bot bot,
            @NotNull OnebotEvent.GroupMessageEvent event)
    {
        String msg = event.getRawMessage();
        Long groupId = event.getGroupId();
        if (msg.startsWith("热搜"))
        {
            String content = "";
            msg = msg.substring(2).trim();
            if (msg.equals("掘金"))
            {
                content = buildTophub("juejin");
            }
            else if (msg.equals("v2ex"))
            {
                content = buildTophub("v2ex");
            }
            else if (msg.equals("头条"))
            {
                content = buildTophub("toutiao");
            }
            else if (msg.equals("百度"))
            {
                content = buildTophub("baidu");
            }
            else if (msg.equalsIgnoreCase("36k"))
            {
                content = buildTophub("36k");
            }
            else if (msg.equalsIgnoreCase("微博"))
            {
                content = buildTophub("weibo");
            }
            else if (msg.equalsIgnoreCase("知乎"))
            {
                content = buildTophub("zhihu");
            }
            else if (msg.equalsIgnoreCase("网易"))
            {
                content = buildTophub("163");
            }
            else if (msg.equalsIgnoreCase("B站"))
            {
                content = buildTophub("bilibili");
            }
            else if (msg.equalsIgnoreCase("微信"))
            {
                content = buildTophub("weixin");
            }
            if (StrUtil.isNotBlank(content))
            {
                bot.sendGroupMsg(groupId, content, false);
            }
            return MESSAGE_BLOCK;
        }
        // 继续执行下一个插件
        return MESSAGE_IGNORE;
    }

    private String buildTophub(String type)
    {
        Date now = new Date();
        Hothub hothub = hotMap.get(type);
        if (null != hothub && (now).before(hothub.getExpire()))
        {
            return getHotpub(hothub.getContent());
        }
        String result = HttpUtil.sendGet(
                StrUtil.format(AlApiConst.URL_TOPHUB, ALAPI_TOKEN, type));
        if (StrUtil.isNotBlank(result))
        {
            hothub = new Hothub().setContent(result)
                    .setExpire(DateUtil.offsetHour(now, 1));
            hotMap.put(type, hothub);
            return getHotpub(result);
        }
        return "机器人暂时失联了，请稍后再试";
    }

    /**
     * @param result
     * @return
     * @author zmr
     */
    private String getHotpub(String result)
    {
        JsonObject json = JsonParser.parseString(result).getAsJsonObject();
        StringBuffer sb = new StringBuffer();
        String text = "";
        if (json.get("code").getAsInt() == 200)
        {
            JsonObject data = json.get("data").getAsJsonObject();
            sb.append("我猜你想看这个").append("\r\n");
            sb.append(data.get("name").getAsString()).append("\r\n");
            JsonArray list = data.getAsJsonArray("list");
            int index = new Random().nextInt(list.size());
            JsonObject hot = list.get(index).getAsJsonObject();
            sb.append("标题：").append(hot.get("title").getAsString())
                    .append("\r\n");
            sb.append("链接：").append(hot.get("link").getAsString())
                    .append("\r\n");
            text = sb.toString();
        }
        return text;
    }
}
